const db = require('../../db/db.js')
const jwt = require('jsonwebtoken')
const { encryptToken } = require('../../utils/encrypt.js');
const Core = require('@alicloud/pop-core');
const { setPhoneCode } = require('../../utils/codeClient.js')
const { v4: uuidv4 } = require('uuid');
const SMSClient = require('@alicloud/sms-sdk');


// 获取验证码
exports.getCode = (request, response) => {
  let phoneNum = request.body.phone;  //获取前端参数phone
  let type = request.body.type;  //获取前端参数phone

  //初始化sms_client
  let smsClient = new SMSClient({
    accessKeyId: 'LTAI5tDDLu1Q1zWjWhYfx9TD',  //accessKeyId 前面提到要准备的
    secretAccessKey: 'paCMRfMN9Hc3MjA6HhhZU0GR5WPNxA'  //secretAccessKey 前面提到要准备的
  });

  //6位随机数
  let phoneCode = setPhoneCode();

  // 开始发送短信
  smsClient.sendSMS({
    PhoneNumbers: phoneNum,
    SignName: "微行鲜果", //签名名称 前面提到要准备的
    TemplateCode: "SMS_302715737", //模版CODE  前面提到要准备的
    TemplateParam: `{"code":'${phoneCode}'}`, // 短信模板变量对应的实际值，JSON格式
  }).then(result => {
    let { Code } = result;
    if (Code == 'OK') {
      let updateSql = `update ${type} set code=? where username=?`
      db.query(updateSql, [phoneCode, phoneNum], (err, result) => {
        if (err) {
          return response.send(err);
        }
        response.json({
          code: 200,
          msg: 'success',
          sms: phoneCode
        })
      });
    }
  }).catch(err => {
    response.json({
      code: 400,
      msg: 'fail: ' + err
    })
  })
}

// 注册账号
exports.register = (request, response) => {
  let userinfo = request.body
  let sqlWhere = userinfo?.type
  let getUserSql = `select * from users where ${sqlWhere}=?`
  let value = userinfo[sqlWhere]
  db.query(getUserSql, [value], (err, res) => {
    if (err) {
      return response.send(err)
    }
    if (res?.length > 0) {
      return response.send({
        code: 200,
        message: '该用户已存在'
      })
    } else {
      let uid = uuidv4() // 生成uuid
      userinfo.uid = uid
      let registerSql = `insert into users set ?`

      db.query(registerSql, userinfo, (err, res) => {
        if (err) return response.send(err)
        return response.send({
          code: 200,
          message: '注册成功'
        })
      })
    }
  })
}

// 账号密码登录
exports.login = (request, response) => {
  // 获取传入的用户账号密码
  let userinfo = request.body
  let sqlWhere = userinfo?.type
  const tokenHeader = request.headers?.authorization || '';
  const token = tokenHeader.startsWith('Bearer ') ? tokenHeader.slice(7) : tokenHeader;

  if (sqlWhere == 'token') {
    // 验证token
    jwt.verify(token, encryptToken.jwtSecretKey, (err, decoded) => {
      if (err) {
        return response.status(401).json({
          msg: 'Token已过期'
        });
      }

      // 如果需要在数据库中检查 token
      const sql = 'SELECT * FROM users WHERE token=?';
      let sqlToken = tokenHeader.startsWith('Bearer ') ? tokenHeader : 'Bearer ' + tokenHeader;
      db.query(sql, [sqlToken], (dbError, results) => {
        if (dbError) {
          return response.status(500).json({
            msg: err
          });
        }
        if (results.length > 0) {
          return response.send({
            code: 200,
            message: '登录成功！',
            data: {
              ...results[0],
              // token
            }
          })
        } else {
          return response.status(401).json({
            msg: 'Token 验证失败'
          });
        }
      });
    });
  } else {
    // 暂时只是用户名登录
    let getUserSql = `select * from users where ${sqlWhere}=?`
    let value = userinfo[sqlWhere]
    db.query(getUserSql, [value], (err, res) => {
      if (err) return response.send(err)
      if (!res.length) {
        return response.send({
          code: 100,
          message: '该用户不存在'
        })
      } else {
        let key = sqlWhere == 'username' ? 'password' : 'code'
        let message = sqlWhere == 'username' ? '密码' : '验证码'
        // 目前只是账号密码登录
        if (res[0][key] != userinfo[key]) {
          return response.send({
            code: 100,
            message: message + '错误'
          })
        } else {
          // 生成token
          tokenStr = jwt.sign(userinfo, encryptToken.jwtSecretKey, { expiresIn: encryptToken.expiresIn })
          let token = `Bearer ${tokenStr}`

          let setTokenSql = `update users set token=? where username=?`
          db.query(setTokenSql, [token, userinfo.username], (err, res) => {
            if (err) return response.send(err)
            return response.send({
              code: 200,
              message: '登录成功！',
              data: {
                ...res[0],
                // token
              }
            })
          })
        }
      }
    })
  }
}